<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 角色管理 </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button type="primary" icon="el-icon-delete" class="handle-del mr10" @click="delAllSelection">批量删除</el-button>
                <el-input v-model="query.name" placeholder="角色名" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="primary" icon="el-icon-lx-roundadd" @click="handlerRoleAdd">添加</el-button>
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="roleId" label="ID" align="center"></el-table-column>
                <el-table-column prop="roleName" label="角色名字" align="center"></el-table-column>
                <el-table-column prop="permMenus" label="权限值" align="center"></el-table-column>
                <el-table-column prop="createTime" label="创建时间" align="center"></el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.$index, scope.row)"
                            >删除</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
            <!-- <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.pageIndex"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div> -->
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="40%">
            <el-form ref="form" :model="form" label-width="70px">
                <el-form-item label="角色名字">
                    <el-input disabled v-model="form.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述">
                    <el-input disabled v-model="form.roleDes"></el-input>
                </el-form-item>
                <el-form-item label="权限">
                    <el-tree 
                    :data="data" 
                    ref="tree1"
                    default-expand-all 
                    show-checkbox 
                    node-key="menuId" 
                    @check-change="checkedChange" 
                    :props="defaultProps">
                    </el-tree>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancelEdit">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { fetchData } from '../../api/index';
export default {
    name: 'basetable',
    data() {
        return {
            data: [],
            defaultProps: {
                children: 'subs',
                label: 'title'
            },
            query: {
                name: '' //角色的名字
            },
            editMenuChecked: [], //编辑的时候 选中的这个菜单和权限
            menuAndPerms: [], //这个里面存放角色具有的权限和菜单
            tableData: [],
            multipleSelection: [],
            delList: [],
            editVisible: false,
            pageTotal: 0,
            form: {},
            idx: -1,
            id: -1,
            backData:{}
        };
    },
    created() {
        this.getData();
        this.initMenuAndPerm();
    },

    beforeRouteEnter(to, from, next) {
        next((vm) => {
            vm.getData();
        });
    },
    methods: {
        cancelEdit() {
            //这里需要将原始数据复原
            this.$set(this.tableData,this.idx,this.backData)
            this.editVisible = false;
            this.menuAndPerms = [];
        },
        initMenuAndPerm() {
            this.$axios.get('/api/permMenuService/permMenu/list.action').then(
                (resp) => {
                    if (!resp.data.code) {
                        this.data = resp.data.dataMap.menuList;
                    } else {
                        this.$message.error('获取菜单权限数据失败');
                    }
                },
                (error) => {
                    this.$message.error('获取菜单权限数据失败');
                }
            );
        },
        //这个就是树形菜单选项发生改变之后要触发的事件
        //这一个参数就表示的是当前选中的选项是谁
        checkedChange() {
            //树形菜单选择框发生改变时触发的事件
            const allCheckNodes = this.$refs.tree1.getCheckedNodes(false, true); //利用这个方式就可以获得选中的节点
            //先将存储选中数据的对象清空
            this.editMenuChecked = [];
            for (var i = 0; i < allCheckNodes.length; i++) {
                this.editMenuChecked[i] = allCheckNodes[i].menuId;
            }
            console.log('选中的节点：' + this.form.menuChecked);
        },
        
        //点击了添加按钮之后 触发的事件
        handlerRoleAdd() {
            //这里需要跳转到添加用户的页面去
            //this.$router.push('/addUser');
            this.$router.replace({
                name: 'addRole'
            });
        },

        // 获取 easy-mock 的模拟数据
        getData() {
            //在这里需要去服务器端获取我们的数据
            this.$axios
                .get('/api/roleservice/roles/listRoleWithPermMenu.action', {
                    params: {
                        roleName: this.query.name
                    }
                })
                .then(
                    (resp) => {
                        if (!resp.data.code) {
                            //说明请求服务器是成功的
                            this.tableData = resp.data.dataMap.roleList;
                        }
                    },
                    (error) => {}
                );
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'pageIndex', 1);
            this.getData();
        },

        // 删除操作
        handleDelete(index, row) {
                // 二次确认删除
                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                })
                .then(() => {
                    //这里需要发送请求到服务器去删除数据
                    this.$axios
                        .get('/api/roleservice/roles/deleteByRoleId.action', {
                            params: {
                                roleId: row.roleId
                            }
                        })
                        .then(
                            (resp) => {
                                if (!resp.data.code) {
                                    this.tableData.splice(index, 1);
                                    //this.$message.success('删除成功');
                                } else {
                                    this.$message.error('删除失败');
                                }
                            },
                            (error) => {
                                this.$message.error('删除失败:' + error.message);
                            }
                        );
                })
                .catch(() => {});
        },

        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        delAllSelection() {
            const length = this.multipleSelection.length;
            let str = '';
            this.delList = this.delList.concat(this.multipleSelection);
            for (let i = 0; i < length; i++) {
                str += this.multipleSelection[i].roleId + ' ';
            }

            //这里就应该从这里写 发送请求到服务器去批量删除角色
            this.$axios
                .get('/api/roleservice/roles/deleteByRoleIds.action', {
                    params: {
                        roleIds: str
                    }
                })
                .then(
                    (resp) => {
                        if (!resp.data.code) {
                            this.multipleSelection = [];
                            this.getData();
                        } else {
                            this.$message.error('删除数据失败');
                        }
                    },
                    (error) => {
                        this.$message.error('删除数据失败:' + error.message);
                    }
                );
        },

        handleEdit(index, row) {
            let obj=this;
            //这里还需要将原始数据进行深度拷贝
            this.backData={ ...row}
            //在这里我们需要根据传递过来的这个Role的id去查询他拥有的权限的menuId值
            this.$axios.get('/api/roleservice/roles/findMenuIdByRoleId.action?roleId=' + row.roleId).then(
                (resp) => {
                    if (!resp.data.code) {
                        //接下来我就要将这个数据设置给这个el_tree
                        //首先是要找到这个对象
                        //说明请求成功
                        console.log('查询到的权限和角色数据是:' + resp.data.dataMap.menuIds);
                        //是不是还要将这个数据设置到Tree上面去
                        this.idx = index;
                        this.form = row;
                        this.editVisible = true;
                        //obj.$refs.tree1.setCheckedKeys(resp.data.dataMap.menuList);
                        //obj.$refs.tree.setCheckedKeys(resp.data.dataMap.menuList);
                        //研究下
                        obj.$nextTick(() => {
                            obj.$refs.tree1.setCheckedKeys(resp.data.dataMap.menuIds,false);
                            //在这里应该要赋值这个数组  editMenuChecked
                         });
                    } else {
                        this.$message.error('通过角色id查询用户的权限和菜单失败....');
                    }
                },
                (error) => {
                    this.$message.error('通过角色id查询用户的权限和菜单失败....');
                }
            );
        },

        // 保存编辑
        saveEdit() {
            //这里需要更新数据
            //构建请求请求服务器
            let form1 = new FormData();
            form1.append('menuChecked', this.editMenuChecked);
            form1.append('roleId', this.form.roleId);
            //接下来就是发送请求到服务器实现用户的添加
            this.$axios({
                method: 'POST',
                url: '/api/roleservice/roles/updateRole.action',
                data: form1,
                header: {
                    'Content-Type': 'multipart/form-data' //这个叫做以表单的形式上传数据
                }
            }).then(
                (resp) => {
                    if (!resp.data.code) {
                        //这里表示的是更新成功
                        this.editVisible = false;
                        this.$message.success(`修改第 ${this.idx + 1} 行成功`);
                        this.$set(this.tableData, this.idx, this.form);
                        this.getData();
                    } else {
                        //上传失败
                        this.$message.error('添加角色数据失败');
                    }
                },
                (error) => {
                    //上传的时候可能遇到网络阻塞
                    this.$message.error('添加角色数据失败');
                }
            );
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'pageIndex', val);
            this.getData();
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
